import {toRaw} from 'vue'
import {useStore} from '@/stores'

import {
  removeAssetOfHolder,
  loadAssetLevelPage,
  loadAssetsForHolderByPage,
  loadHolderForAssetPage,
  saveAssetOfHolder,
  saveHolderForAsset
} from '@/apis/sop'

import {useTerminal} from "@/utils/sop/UseTerminal";
import {msgInfo, msgWarn} from "@/utils/InfoUtil";
import {SERVERS} from "@/stores/conf";
import {handleResult} from "@/utils/SystemUtil";

export function useLoadAssign(entry: any) {
  const store = useStore();
  const {productCode} = useTerminal(entry.name);

  const current = () => {
    const item = store.getCurrent(entry.name)
    return item ? toRaw(item.item) : {}
  }

  const getTargetId = (id: string) => {
    if (id) {
      return id;
    } else if (SERVERS.REALM === entry.server) {
      return store.getCurrentRealms().id;
    } else {
      return store.getCurrentPlatform().id;
    }
  }

  // ----------------------- 下面为角色分配的目标资源操作
  /**
   * 分页读取分配给当前角色的权限列表
   */
  const load = async (targetId: string, type: string, params: any) => {
    const result = await loadAssetsForHolderByPage({
      server: entry.server,
      targetId: getTargetId(targetId),
      holdId: current().id,
      holdType: entry.type,
      assetType: type,
      ...params
    })

    if (result && result.data && result.data.data) {
      result.data.data.forEach((item: any) => {
        if (item.props) {
          item.comment = item.props.comment || '';
          item.createTime = item.props.createTime || '';
        }
      })
    }

    return result;
  }

  /**
   * 保存资源（比如把权限保存到分组、用户下）
   */
  const assign = async (targetId: string, type: string, items: any,
                        productCode: string='default', saveAll: number=0) => {
    const assetItems: any = []
    items.forEach((item: any) => {
      assetItems.push({
        assetId: item.id,
        name: item.name,
      })
    })
    return await saveAssetOfHolder({
      server: entry.server,
      targetId: getTargetId(targetId),
      holdId: current().id,
      holdType: entry.type,
      productCode: productCode,
      assetType: type,
      assets: assetItems,
      saveAll: saveAll,
    })
  }

  /**
   * 分页读取可以分配的资源列表
   */
  const loadAssign = async (targetId: string, type: string, params: any) => {
    const holds: any = [];

    holds.push(current().id);

    const result = await loadAssetLevelPage({
      current: params.current ? params.current : 1,
      pageSize: params.pageSize ? params.pageSize : 10,

      server: entry.server,
      targetId: getTargetId(targetId),
      assetType: type,
      name: params.name,
      parentId: params.parentId,
      productCode: params.productCode || 'default',
      filterRelMode: 1,
      filterRelIds: holds,
      filterRelType: current().type,
    });

    if (result && result.data) {
      handleResult(result.data, ['exist']);
    }

    return result;
  }

  // ----------------------- 下面为持有此角色的目标资源操作
  /**
   * 读取持有当前资源的目标信息（比如client、user、group等）
   * @param params
   * @param targetId
   * @param holdType 持有资源的类型（比如client、user、group等）
   */
  const loadHolders = async (targetId: string, holdType: string, params: any) => {
    const result: any =  await loadHolderForAssetPage({
      server: entry.server,
      targetId: getTargetId(targetId),
      holdType: holdType,
      assetId: current().id,
      assetType: entry.type,
      productCode: productCode(),

      ...params
    })

    if (result && result.data) {
      handleResult(result.data, ['comment', '$lastLoginTime','phone']);
    }

    return result;
  }

  /**
   * 把指定的持有者（比如user、group）关联到当前资源
   * @param items
   * @param targetId
   * @param holdType 持有资源的类型（比如client、user、group等）
   */
  const joinHolders = async (targetId: string, holdType: string, items: any) => {
    const holders: any = []
    items.forEach((item: any) => {
      holders.push({
        holdId: item.id,
        name: item.name,
      })
    })
    return await saveHolderForAsset({
      server: entry.server,
      targetId: getTargetId(targetId),
      assetId: current().id,
      assetType: entry.type,
      productCode: productCode(),
      holdType: holdType,
      holders: holders
    })
  }

  /**
   * 查询能够加入的目标信息（）
   * @param params
   * @param targetId
   * @param holdType 持有资源的类型（比如client、user、group等）
   */
  const loadJoinHolders = async (targetId: string, holdType: string, params: any) => {
    /*
     * 读取持有资源的目标信息，这里要把持有的资源（比如权限、角色）排除掉
     */
    const targets: any = [current().id];

    const result = await loadAssetLevelPage({
      current: params.current ? params.current : 1,
      pageSize: params.pageSize ? params.pageSize : 10,
      server: entry.server,
      targetId: getTargetId(targetId),
      assetType: holdType,
      filterRelMode: 2,
      filterRelIds: targets,
      filterRelType: current().type,
      name: params.name,
      parentId: params.parentId || '',
      productCode: productCode(),
    });

    if (result && result.data) {
      handleResult(result.data, ['exist']);
    }

    return result;
  }

  /**
   * 移除持有的资源
   * @param targetId
   * @param holdType
   * @param entry 资源类型信息（比如权限、菜单等）
   * @param row 当前需要移除的资源（比如权限、菜单）
   */
  const removeAssetFromHolder = async (targetId: string, holdType: any, entry: any, row: any) => {
    const result = await removeAssetOfHolder({
      server: entry.server,
      targetId: getTargetId(targetId),
      holdId: row.id,
      holdType: holdType,
      productCode: productCode(),
      assetType: entry.type,
      assets: [{
        assetId: current().id,
        name: '',
      }]
    });
    if (result.code === 0) {
      msgInfo(`移除'${row.name}'成功！`);
    } else {
      msgWarn(result.message ? result.message : `移除'${row.name}'失败！`);
    }
  }

  /**
   * 移除资源的持有（比如从用户中移除权限）（current表示的就是用户）
   * @param targetId
   * @param assetType 资源那类型（比如权限）
   * @param entry 资源类型信息（比如用户、角色等）
   * @param row 当前需要移除的资源（比如权限、菜单）
   */
  const removeHolderOfAsset = async (targetId: string, assetType: any, entry: any, row: any) => {
    const result = await removeAssetOfHolder({
      server: entry.server,
      targetId: getTargetId(targetId),
      holdId: current().id,
      holdType: entry.type,
      productCode: productCode(),
      assetType: assetType,
      assets: [{
        assetId: row.id,
        name: '',
      }]
    });
    if (result.code === 0) {
      msgInfo(`移除'${row.name}'成功！`);
    } else {
      msgWarn(result.message ? result.message : `移除'${row.name}'失败！`);
    }
  }

  return {
    current,
    load,
    assign,
    loadAssign,
    loadHolders,
    joinHolders,
    loadJoinHolders,
    removeHolderOfAsset,
    removeAssetFromHolder
  }
}
